# import os
# from mysql_model import *

from ad_manage_views import *
from guest_views import *

app.secret_key = os.urandom(1)

login_manager = LoginManager(app)
login_manager.login_view = 'login'

app.register_blueprint(ad_manage_views)
app.register_blueprint(guest_views)


# 用户登登录查询
@login_manager.user_loader
def load_user(user_id):
    user = Users.query.get(int(user_id))
    return user


@app.route('/', methods=DEFAULT_METHODS)
def index():
    """
    主页，展示自主注册和登录后台的按钮
    :return:
    """

    return render_template('index.html')


@app.route('/manage', methods=DEFAULT_METHODS)
@login_required
def manage():
    """
    管理页面，真正的主页
    :return:
    """
    return render_template('base.html',username=current_user.username)


@app.route('/login', methods=DEFAULT_METHODS)
def login():
    """
    登录页面
    :return:
    """
    return render_template('login.html')


@app.route('/login_confirm', methods=['POST'])
def login_confirm():
    """
    登录验证
    :return:
    """
    username = request.form.get('username')
    password = request.form.get('password')
    if username == 'None':
        msg = '无用户名输入，请输入用户名密码登录'
        data = {'code': 1, 'msg': msg}
        return data
    else:
        # print('获取到有输入用户名密码，进行校验')
        user = Users.query.filter_by(username=username).first()
        if user:
            # print('能查询到用户名，接下来校验密码')
            if username == user.username and user.validate_password(password):
                login_user(user)
                msg = '用户名密码校验通过，登录成功'
                return redirect(url_for('manage'))
            else:
                msg = '密码错误'
                data = {'code': 1, 'msg': msg}
                flash(data)
                return redirect(url_for('login'))
        else:
            msg = '用户名或密码错误'
            data = {'code': 1, 'msg': msg}
            flash(data)
            return redirect(url_for('login'))


@app.route('/modify_admin_name', methods=API_METHODS)
@login_required
def modify_admin_name():
    """
    修改网站用户的密码
    :return:
    """
    # 获取登录的用户名
    username = current_user.username
    # 获取密码
    new_name = request.form.get('username')
    try:
        # 查询用户并修改密码
        user = Users.query.filter(Users.username == username).first()
        user.username = new_name
        # 提交任务
        db.session.commit()
        msg = '修改成功'
        data = {'code': 1, 'msg': msg}
    except Exception as e:
        data = {'code': 2, 'msg': f'出现异常，{e}'}
    return data


@app.route('/modify_password', methods=API_METHODS)
@login_required
def modify_password():
    """
    修改网站用户的密码
    :return:
    """
    # 获取登录的用户名
    username = current_user.username
    # 获取密码
    old_password = request.form.get('old_password')
    password = request.form.get('password')
    user = Users.query.filter_by(username=username).first()
    if username == user.username and user.validate_password(old_password):
        try:
            # 查询用户并修改密码
            user = Users.query.filter(Users.username == username).first()
            user.set_password(password)
            # 提交任务
            db.session.commit()
            msg = '修改成功'
            data = {'code': 1, 'msg': msg}
        except Exception as e:
            data = {'code': 2, 'msg': f'出现异常，{e}'}
    else:
        data = {'code': 2, 'msg': f'旧密码不正确'}
    return data


@app.route('/logout', methods=DEFAULT_METHODS)
def logout():
    """
    退出登录
    :return:
    """
    logout_user()
    return redirect(url_for('login'))


@app.route('/add_server', methods=DEFAULT_METHODS)
@login_required
def add_server():
    """
    添加服务器信息到本地数据库。
    实际上只允许数据库里存在一条服务器记录。
    :return:
    """
    server_config = ServerConfig.query.filter(ServerConfig.server_name == '默认服务器').first()
    if server_config:
        flash('已存在服务器，无需添加')
        return redirect(url_for('index'))
    if request.form.get('submit') == 'submit':
        host = request.form.get('host')
        port = request.form.get('port') or '636'
        username = request.form.get('username')
        password = request.form.get('password')
        result, msg = check_server(host, eval(port), username, password)
        if result:
            flash(msg)
            return redirect(url_for('add_server'))
        else:
            return redirect(url_for('ad_manage_views.refresh_ldap_conn'))
    else:
        flash('请输入服务器信息')
        return render_template('initServer.html')


@app.route('/manage_server', methods=DEFAULT_METHODS)
@login_required
def manage_server():
    """
    从本地数据库获取服务器信息
    :return:
    """
    msg = ServerConfig.query.filter(ServerConfig.server_name == '默认服务器').first()  # msg给前端判断是否有服务器信息
    return render_template('manage.html', msg=msg)


@app.route('/delete_server', methods=DEFAULT_METHODS)
@login_required
def delete_server():
    """
    从本地数据库删除服务器
    :return:
    """
    ServerConfig.query.filter(ServerConfig.server_name == '默认服务器').delete()
    db.session.commit()
    return redirect(url_for('ad_manage_views.refresh_ldap_conn'))


@app.route('/get_server', methods=API_METHODS)
@login_required
def get_server():
    """
    从本地数据库获取AD服务器信息
    :return:
    """
    try:
        server_config = ServerConfig.query.filter(ServerConfig.server_name == '默认服务器').first()
        data = {"code": 0, "msg": "success", "count": 1, "data": [server_config]}
    except Exception as e:
        data = {"code": 1, "msg": e, "count": 0, "data": []}
    return data


@app.route('/get_web', methods=API_METHODS)
@login_required
def get_web():
    """
    从本地数据库获取AD服务器信息
    :return:
    """
    try:
        server_config = WebConfig.query.filter(WebConfig.id == '1').first()
        data = {"code": 0, "msg": "success", "count": 1, "data": [server_config]}
    except Exception as e:
        data = {"code": 1, "msg": e, "count": 0, "data": []}
    return data


@app.route('/change_port', methods=API_METHODS)
@login_required
def change_port():
    """
    从本地数据库获取AD服务器信息
    :return:
    """
    try:
        port = request.form.get('port')
        server_config = WebConfig.query.filter(WebConfig.id == '1').first()
        server_config.port = int(port)
        db.session.add(server_config)
        db.session.commit()
        msg = '修改端口号成功,重启服务端程序后生效'
        data = {'code': 1, 'msg': msg}
    except Exception as e:
        data = {'code': 2, "msg": e}
    return data


if __name__ == '__main__':
    msg = init()
    print(msg)
    try:
        result = WebConfig.query.filter(WebConfig.id == '1').first()
    except Exception as e:
        print(e)
    if result:
        app.run(host='0.0.0.0', port=result.port, debug=True)
    else:
        app.run(host='0.0.0.0', port=80, debug=True)

    # app.run(host='0.0.0.0', port=80)
    # app.run(host=yml['app_config']['host'], port=yml['app_config']['port'])
